package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gitee.starblues.factory.PluginRegistryInfo;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.DepotHeadVo4List;
import com.jsh.erp.datasource.vo.DepotItemStockWarningCount;
import com.jsh.erp.datasource.vo.DepotItemVoBatchNumberList;
import com.jsh.erp.datasource.vo.SalesTaxMoney;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.materialExtend.MaterialExtendService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.person.PersonService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.unit.UnitService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.*;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;
import static com.jsh.erp.utils.Tools.getCenternTime;

/**
 * @author ji-sheng-hua 华夏erp
 */
@RestController
@RequestMapping(value = "/depotItem")
@Api(tags = {"单据明细"})
public class DepotItemController {
    private Logger logger = LoggerFactory.getLogger(DepotItemController.class);

    @Resource
    private DepotItemService depotItemService;

    @Resource
    private MaterialService materialService;

    @Resource
    private MaterialExtendService materialExtendService;

    @Resource
    private UnitService unitService;

    @Resource
    private DepotService depotService;

    @Resource
    private RedisService redisService;

    @Resource
    private UserService userService;

    @Resource
    private DepotHeadService depotHeadService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private PersonService personService;
    @Resource
    private AccountHeadService accountHeadService;

    /**
     * 根据仓库和商品查询单据列表
     * @param mId
     * @param request
     * @return
     */
    @GetMapping(value = "/findDetailByDepotIdsAndMaterialId")
    @ApiOperation(value = "根据仓库和商品查询单据列表")
    public String findDetailByDepotIdsAndMaterialId(
            @RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
            @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
            @RequestParam(value = "depotIds",required = false) String depotIds,
            @RequestParam(value = "sku",required = false) String sku,
            @RequestParam("materialId") String mId,
            HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        List<String> depotList = parseListByDepotIds(depotIds);
//        List<String> depotList = new ArrayList<>();
        if(StringUtil.isNotEmpty(depotIds)) {
            depotList = StringUtil.strToStringList(depotIds);
        }
        List<DepotItemVo4DetailByTypeAndMId> list = depotItemService.findDetailByDepotIdsAndMaterialIdList(depotList, sku, mId, (currentPage-1)*pageSize, pageSize);
        JSONArray dataArray = new JSONArray();
        if (list != null) {
            for (DepotItemVo4DetailByTypeAndMId d: list) {
                JSONObject item = new JSONObject();
                item.put("number", d.getNumber()); //编号
                item.put("barCode", d.getBarCode()); //条码
                item.put("materialName", d.getMaterialName()); //名称
                String type = d.getType();
                String subType = d.getSubType();
                if(("其它").equals(type) ||("到货").equals(type)) {
                    item.put("type", subType); //进出类型
                } else {
                    item.put("type", subType + type); //进出类型
                }
                item.put("depotName", d.getDepotName()); //仓库名称
                item.put("basicNumber", d.getBnum()); //数量
                item.put("operTime", Tools.getCenternTime(d.getOtime())); //时间
                item.put("custom11", d.getCustom11()); //时间
                item.put("differNumber", d.getDifferNumber()); //时间
                dataArray.add(item);
            }
        }
        if (list == null) {
            objectMap.put("rows", new ArrayList<Object>());
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }

        objectMap.put("rows", dataArray);
        objectMap.put("total", depotItemService.findDetailByDepotIdsAndMaterialIdCount(depotList, sku, mId));
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }


    /**
     * @Author: wy
     * @Description: 促销统计详情
     * @DateTime: 2022/8/5 15:42
     * @Params:
     * @Return
     */
    @GetMapping(value = "/findPromotionDetail")
    @ApiOperation(value = "促销统计详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotItemVo4DetailByTypeAndMId.class)
    })
    public String findPromotionDetail(@RequestParam("currentPage") Integer currentPage,
                                                @RequestParam("pageSize") Integer pageSize,
                                                @RequestParam("materialId") String materialId,
                                                HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        Map<String, Object> map = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
            List<DepotItemVo4DetailByTypeAndMId> resList = new ArrayList<DepotItemVo4DetailByTypeAndMId>();
            List<DepotItemVo4DetailByTypeAndMId> list = depotItemService.findByMaterialAll(materialId,(currentPage-1)*pageSize, pageSize);
            JSONArray dataArray = new JSONArray();
            if (list != null) {
                for (DepotItemVo4DetailByTypeAndMId d: list) {
                    JSONObject item = new JSONObject();
                    item.put("number", d.getNumber()); //编号
                    item.put("barCode", d.getBarCode()); //条码
                    item.put("materialName", d.getMaterialName()); //名称
                    String type = d.getType();
                    String subType = d.getSubType();
                    if(("其它").equals(type)) {
                        item.put("type", subType); //进出类型
                    } else {
                        item.put("type", subType + type); //进出类型
                    }
                    item.put("depotName", d.getDepotName()); //仓库名称
                    item.put("bnum", d.getBnum()); //数量
                    item.put("operTime", Tools.getCenternTime(d.getOtime())); //时间
                    item.put("unitPrice", d.getUnitPrice()); //单价
                    dataArray.add(item);
                }
            }
            if (list == null) {
                objectMap.put("rows", new ArrayList<Object>());
                objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
                return returnJson(objectMap,"zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
            }
        objectMap.put("rows", dataArray);
        objectMap.put("total", depotItemService.findByMaterialAllCount(materialId));
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    /**
     * 根据商品条码和仓库id查询库存数量
     * @param meId
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/findStockByDepotAndBarCode")
    @ApiOperation(value = "根据商品价格id和仓库id查询库存数量")
    public BaseResponseInfo findStockByDepotAndBarCode(
            @RequestParam(value = "depotId",required = false) String depotId,
            @RequestParam("meId") String meId,
            HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BigDecimal stock = BigDecimal.ZERO;
            List<MaterialVo4Unit> list = materialService.getMaterialByMeIdList(meId);
            if(list!=null && list.size()>0) {
                MaterialVo4Unit materialVo4Unit = list.get(0);
                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByMaterialList(list,depotId);
                stock = currentStockMap.get(materialVo4Unit.getId())!=null? currentStockMap.get(materialVo4Unit.getId()): BigDecimal.ZERO;
//                if(StringUtil.isNotEmpty(materialVo4Unit.getSku())){
//                    stock = depotItemService.getSkuStockByParam(depotId,materialVo4Unit.getMeId(),null,null);
//                } else {
//                    stock = depotItemService.getStockByParam(depotId,materialVo4Unit.getId(),null,null);
//                    if(materialVo4Unit.getUnitId()!=null) {
//                        Unit unit = unitService.getUnit(materialVo4Unit.getUnitId());
//                        String commodityUnit = materialVo4Unit.getCommodityUnit();
//                        stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
//                    }
//                }
            }
            map.put("stock", stock);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 单据明细列表
     * @param headerId
     * @param mpList
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getDetailList")
    @ApiOperation(value = "单据明细列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "执行成功",response = DepotItemVo4WithInfoEx.class)
    })
    public BaseResponseInfo getDetailList(@RequestParam("headerId") String headerId,
                                          @RequestParam(value = "supplierId",required = false) String supplierId,
                              @RequestParam("mpList") String mpList,
                              @RequestParam(value = "linkType", required = false) String linkType,
                              HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotItemVo4WithInfoEx> dataList = new ArrayList<DepotItemVo4WithInfoEx>();
            if(!StringUtil.isEmpty(headerId)) {
                dataList = depotItemService.getHeadDetailList(headerId);
            }
            DepotHead depotHead = depotHeadService.getDepotHeadByIdNotTenant(headerId);
            String[] mpArr = mpList.split(",");
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (dataList.size() > 0) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", diEx.getId());
                    item.put("headerId", headerId);
                    item.put("materialExtendId", diEx.getMaterialExtendId() == null ? "" : diEx.getMaterialExtendId());
                    item.put("barCode", diEx.getBarCode());
                    item.put("name", diEx.getMName());
                    item.put("standard", diEx.getMStandard());
                    item.put("model", diEx.getMModel());
                    item.put("color", diEx.getMColor());
                    item.put("materialOther", getOtherInfo(mpArr, diEx));
                    BigDecimal stock = materialService.getCurrentStockMapByMaterialId(diEx.getMaterialId(),diEx.getDepotId());
                    Unit unitInfo = materialService.findUnit(diEx.getMaterialId()); //查询计量单位信息
                    String materialUnit = diEx.getMaterialUnit();
                    item.put("stock", stock);
                    item.put("unit", diEx.getMaterialUnit());
                    item.put("snList", diEx.getSnList());
                    item.put("batchNumber", diEx.getBatchNumber());
                    item.put("expirationDate", Tools.parseDateToStr(diEx.getExpirationDate()));
                    item.put("sku", diEx.getSku());
                    item.put("enableSerialNumber", diEx.getEnableSerialNumber());
                    item.put("enableBatchNumber", diEx.getEnableBatchNumber());
                    item.put("operNumber", diEx.getOperNumber());
                    item.put("basicNumber", diEx.getBasicNumber());
                    item.put("preNumber", diEx.getOperNumber()); //原数量
                    if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())){
                        item.put("finishNumber", depotItemService.getSaleFinishNumber(diEx.getMaterialExtendId(), diEx.getId(), diEx.getHeaderId(), unitInfo, materialUnit, linkType)); //已入库|已出库
                    }else if ("要货申请".equals(depotHead.getSubType()) ||"配送".equals(depotHead.getSubType()) ||"验收".equals(depotHead.getSubType())){
                        item.put("finishNumber", depotItemService.getNotTenantFinishNumber(diEx.getMaterialExtendId(), diEx.getId(), diEx.getHeaderId(), unitInfo, materialUnit, linkType));
                    }else {
                        item.put("finishNumber", depotItemService.getFinishNumber(diEx.getMaterialExtendId(), diEx.getId(), diEx.getHeaderId(), unitInfo, materialUnit, linkType)); //已入库|已出库
                    }
                    //采购价
                    item.put("purchaseDecimal", diEx.getPurchaseDecimal());
                    item.put("unitPrice", diEx.getUnitPrice());
                    item.put("taxUnitPrice", diEx.getTaxUnitPrice());
                    item.put("allPrice", diEx.getAllPrice());
                    item.put("remark", diEx.getRemark());
                    item.put("linkId", diEx.getLinkId());
                    item.put("depotId", diEx.getDepotId() == null ? "" : diEx.getDepotId());
                    item.put("depotName", diEx.getDepotId() == null ? "" : diEx.getDepotName());
                    item.put("anotherDepotId", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotId());
                    item.put("anotherDepotName", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotName());
//                    SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
//                    if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
//                        res.code = 500;
//                        res.data = "zh".equals(lanCode) ? "未设置税率" : "Untaxed rate";
//                        return res;
//                    }
//                    BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());
                    item.put("taxRate", diEx.getTaxRate());
                    item.put("taxMoney", diEx.getTaxMoney());
                    item.put("taxLastMoney", diEx.getTaxLastMoney());
                    item.put("mType", diEx.getMaterialType());
                    item.put("priceNote", diEx.getPriceNote());
                    item.put("materialId", diEx.getMaterialId());
                    //采购订单原数量
                    item.put("custom6", diEx.getCustom6());
                    //采购订单原含税单价
                    item.put("custom7", diEx.getCustom7());
                    item.put("op", 1);
                    if (depotHead.getArrivalTime()!=null){
                        item.put("arrivalTime",getCenternTime(depotHead.getArrivalTime()));
                    }
                    item.put("deliveryMethod",depotHead.getDeliveryMethod());
                    item.put("differNumber",diEx.getDifferNumber());
                    item.put("organId",diEx.getOrganId());
                    item.put("organName",diEx.getOrganName());
                    item.put("custom1",diEx.getCustom1());
                    item.put("custom2",diEx.getCustom2());
                    item.put("custom3",diEx.getCustom3());
                    item.put("sourceId",diEx.getCustom4());
                    item.put("custom4",diEx.getCustom4());
                    item.put("custom5",diEx.getCustom5());
                    item.put("custom6",diEx.getCustom6());
                    item.put("custom7",diEx.getCustom7());
                    item.put("custom8",diEx.getCustom8());
                    item.put("custom9",diEx.getCustom9());
                    item.put("custom10",diEx.getCustom10());
                    item.put("custom11",diEx.getCustom11());
                    item.put("custom12",diEx.getCustom12());
                    item.put("custom13",diEx.getCustom13());
                    item.put("custom14",diEx.getCustom14());
                    item.put("custom15",diEx.getCustom15());
                    item.put("discountPrice",diEx.getDiscountPrice());
                    item.put("discountAllPrice",diEx.getDiscountAllPrice());
                    item.put("categoryName",diEx.getCategoryName());
                    dataArray.add(item);
                }
            }

            outer.put("rows", dataArray);
            res.code = 200;
            res.data = outer;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 获取扩展信息
     *
     * @return1`
     */
    public String getOtherInfo(String[] mpArr, DepotItemVo4WithInfoEx diEx)throws Exception {
        String materialOther = "";
        for (int i = 0; i < mpArr.length; i++) {
            if (mpArr[i].equals("制造商")) {
                materialOther = materialOther + ((diEx.getMMfrs() == null || diEx.getMMfrs().equals("")) ? "" : "(" + diEx.getMMfrs() + ")");
            }
            if (mpArr[i].equals("自定义1")) {
                materialOther = materialOther + ((diEx.getMOtherField1() == null || diEx.getMOtherField1().equals("")) ? "" : "(" + diEx.getMOtherField1() + ")");
            }
            if (mpArr[i].equals("自定义2")) {
                materialOther = materialOther + ((diEx.getMOtherField2() == null || diEx.getMOtherField2().equals("")) ? "" : "(" + diEx.getMOtherField2() + ")");
            }
            if (mpArr[i].equals("自定义3")) {
                materialOther = materialOther + ((diEx.getMOtherField3() == null || diEx.getMOtherField3().equals("")) ? "" : "(" + diEx.getMOtherField3() + ")");
            }
        }
        return materialOther;
    }

    /**
     * 进销存统计
     * @param currentPage
     * @param pageSize
     * @param depotIds
     * @param monthTime
     * @param materialParam
     * @param mpList
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/findByAll")
    @ApiOperation(value = "查找所有的明细")
    public BaseResponseInfo findByAll(@RequestParam("currentPage") Integer currentPage,
                                      @RequestParam("pageSize") Integer pageSize,
                                      @RequestParam(value = "depotIds",required = false) String depotIds,
                                      @RequestParam("monthTime") String monthTime,
                                      @RequestParam("materialParam") String materialParam,
                                      @RequestParam("mpList") String mpList,
                                      HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            String timeA = Tools.firstDayOfMonth(monthTime) + BusinessConstants.DAY_FIRST_TIME;
            String timeB = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
            List<String> depotList = new ArrayList<>();
            if(StringUtil.isNotEmpty(depotIds)) {
                depotList = StringUtil.strToStringList(depotIds);
            }else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
                    timeB,(currentPage-1)*pageSize, pageSize);
            String[] mpArr = mpList.split(",");
            int total = depotItemService.findByAllCount(StringUtil.toNull(materialParam), timeB);
            map.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    String mId = diEx.getMId();
                    item.put("barCode", diEx.getBarCode());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(mpArr, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
                    item.put("unitName", diEx.getMaterialUnit());
                    BigDecimal prevSum = depotItemService.getStockByParamWithDepotList(depotList,mId,null,timeA);
                    Map<String,BigDecimal> intervalMap = depotItemService.getIntervalMapByParamWithDepotList(depotList,mId,timeA,timeB);
                    BigDecimal inSum = intervalMap.get("inSum");
                    BigDecimal outSum = intervalMap.get("outSum");
                    BigDecimal thisSum = prevSum.add(inSum).subtract(outSum);
                    item.put("prevSum", prevSum);
                    item.put("inSum", inSum);
                    item.put("outSum", outSum);
                    item.put("thisSum", thisSum);
                    item.put("unitPrice", diEx.getPurchaseDecimal());
                    item.put("thisAllPrice", thisSum.multiply(diEx.getPurchaseDecimal()));
                    dataArray.add(item);
                }
            }
            map.put("rows", dataArray);
            res.code = 200;
            res.data = map;
        } catch (BusinessRunTimeException e) {
            res.code = e.getCode();
            res.data = e.getData().get("message");
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 进销存统计总计金额
     * @param depotIds
     * @param monthTime
     * @param materialParam
     * @param request
     * @return
     */
    @GetMapping(value = "/totalCountMoney")
    @ApiOperation(value = "统计总计金额")
    public BaseResponseInfo totalCountMoney(@RequestParam(value = "depotIds",required = false) String depotIds,
                                            @RequestParam("monthTime") String monthTime,
                                            @RequestParam("materialParam") String materialParam,
                                            HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            String endTime = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
            List<String> depotList = parseListByDepotIds(depotIds);
            List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
                    endTime, null, null);
            BigDecimal thisAllPrice = BigDecimal.ZERO;
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    String mId = diEx.getMId();
                    BigDecimal thisSum = depotItemService.getStockByParamWithDepotList(depotList,mId,null,endTime);
                    BigDecimal unitPrice = diEx.getPurchaseDecimal();
                    if(unitPrice == null) {
                        unitPrice = BigDecimal.ZERO;
                    }
                    thisAllPrice = thisAllPrice.add(thisSum.multiply(unitPrice));
                }
            }
            map.put("totalCount", thisAllPrice);
            res.code = 200;
            res.data = map;
        } catch (BusinessRunTimeException e) {
            res.code = e.getCode();
            res.data = e.getData().get("message");
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    private List<String> parseListByDepotIds(@RequestParam("depotIds") String depotIds) throws Exception {
        List<String> depotList = new ArrayList<>();
        if(StringUtil.isNotEmpty(depotIds)) {
            depotList = StringUtil.strToStringList(depotIds);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
            //如果有权限的仓库数量太多则提示要选择仓库
            if(depotList.size()>100) {
                throw new BusinessRunTimeException(ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG :  ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG_US);
            }
        }
        return depotList;
    }

    /**
     * 进货统计
     * @param currentPage
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @param materialParam
     * @param mpList
     * @param request
     * @return
     */
    @GetMapping(value = "/buyIn")
    @ApiOperation(value = "进货统计")
    public BaseResponseInfo buyIn(@RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize,
                                  @RequestParam("beginTime") String beginTime,
                                  @RequestParam("endTime") String endTime,
                                  @RequestParam("materialParam") String materialParam,
                                  @RequestParam(value = "depotId", required = false) String depotId,
                                  @RequestParam(value = "categoryId", required = false) String categoryId,
                                  @RequestParam("mpList") String mpList,
                                  HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
        try {
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotItemVo4WithInfoEx> dataList = depotItemService.getListWithBugOrSale(StringUtil.toNull(materialParam),
                    "buy", beginTime, endTime, (currentPage-1)*pageSize, pageSize,depotId,idList);
            String[] mpArr = mpList.split(",");
            int total = depotItemService.getListWithBugOrSaleCount(StringUtil.toNull(materialParam), "buy", beginTime, endTime,depotId,idList);
            map.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    BigDecimal InSum = depotItemService.buyOrSale("入库", "采购", diEx.getMId(), beginTime, endTime, "number","其它","收费确认",depotId,idList);
                    BigDecimal OutSum = depotItemService.buyOrSale("出库", "采购退货", diEx.getMId(), beginTime, endTime, "number","其它","直发采购退货",depotId,idList);
                    BigDecimal InSumPrice = depotItemService.buyOrSale("入库", "采购", diEx.getMId(), beginTime, endTime, "price","其它","收费确认",depotId,idList);
                    BigDecimal OutSumPrice = depotItemService.buyOrSale("出库", "采购退货", diEx.getMId(), beginTime, endTime, "price","其它","直发采购退货",depotId,idList);
                    BigDecimal InOutSumPrice = InSumPrice.subtract(OutSumPrice);
                    item.put("barCode", diEx.getBarCode());
                    item.put("color", diEx.getMColor());
                    item.put("materialId", diEx.getMId());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(mpArr, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
                    item.put("materialUnit", diEx.getMaterialUnit());
                    item.put("unitName", diEx.getUnitName());
                    item.put("inSum", InSum);
                    item.put("outSum", OutSum);
                    item.put("inSumPrice", InSumPrice);
                    item.put("outSumPrice", OutSumPrice);
                    item.put("inOutSumPrice",InOutSumPrice);//实际采购金额
                    item.put("depotName",diEx.getDepotName());
                    item.put("categoryName",diEx.getCategoryName());
                    dataArray.add(item);
                }
            }
            map.put("rows", dataArray);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findDetailByMaterialId")
    @ApiOperation(value = "根据仓库和商品查询单据列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotItemVoDetailByMId.class)
    })
    public String findDetailByMaterialId(
            @RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
            @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
            @RequestParam(value = "beginTime") @ApiParam("开始时间") String beginTime,
            @RequestParam("endTime") @ApiParam("结束时间") String endTime,
            @RequestParam("type") @ApiParam("类型")String type,
            @RequestParam("type1") @ApiParam("类型")String type1,
            @RequestParam("subType")@ApiParam("出入库类型") String subType,
            @RequestParam("subType1")@ApiParam("出入库类型") String subType1,
            @RequestParam("materialId") @ApiParam("商品id")String mId,
            HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
        List<DepotItemVoDetailByMId> list = depotItemService.buyDetailList(type, subType, mId, beginTime, endTime, (currentPage - 1) * pageSize, pageSize,type1,subType1);
//        List<DepotItemVo4DetailByTypeAndMId> list = depotItemService.findDetailByDepotIdsAndMaterialIdList(depotIds, sku, mId, (currentPage-1)*pageSize, pageSize);
        if (list != null) {
            for (DepotItemVoDetailByMId d: list) {
                String s = d.getSubType() + d.getType();
                String newType = s.replace("其它", "");
                d.setType(newType);
                d.setOperTimeStr(Tools.getCenternTime(d.getOperTime()));
            }
        }
        if (list == null) {
            objectMap.put("rows", new ArrayList<Object>());
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
        objectMap.put("rows", list);
        objectMap.put("total", depotItemService.buyDetailList(type, subType, mId, beginTime, endTime, null, null,type1,subType1).size());
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    /**
     * 销售统计
     * @param currentPage
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @param materialParam
     * @param mpList
     * @param request
     * @return
     */
//    @GetMapping(value = "/saleOut")
//    @ApiOperation(value = "销售统计")
//    public BaseResponseInfo saleOut(@RequestParam("currentPage") Integer currentPage,
//                                  @RequestParam("pageSize") Integer pageSize,
//                                  @RequestParam("beginTime") String beginTime,
//                                  @RequestParam("endTime") String endTime,
//                                  @RequestParam("materialParam") String materialParam,
//                                  @RequestParam(value = "depotId", required = false) String depotId,
//                                  @RequestParam(value = "categoryId", required = false) String categoryId,
//                                  @RequestParam("mpList") String mpList,
//                                  HttpServletRequest request)throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        String lanCode = redisService.getLanCodeFromSession(request);
//        Map<String, Object> map = new HashMap<String, Object>();
//        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
//        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
//        try {
//            List<String> idList = new ArrayList<>();
//            if(StringUtil.isNotEmpty(categoryId)){
//                idList = materialService.getListByParentId(categoryId);
//            }
//            List<DepotItemVo4WithInfoEx> dataList = depotItemService.getListWithBugOrSale(StringUtil.toNull(materialParam),
//                    "sale", beginTime, endTime,(currentPage-1)*pageSize, pageSize,depotId,idList);
//            String[] mpArr = mpList.split(",");
//            int total = depotItemService.getListWithBugOrSaleCount(StringUtil.toNull(materialParam), "sale", beginTime, endTime,depotId,idList);
//            map.put("total", total);
//            //存放数据json数组
//            JSONArray dataArray = new JSONArray();
//            if (null != dataList) {
//                for (DepotItemVo4WithInfoEx diEx : dataList) {
//                    JSONObject item = new JSONObject();
////                    BigDecimal OutSumRetail = depotItemService.buyOrSale("出库", "零售", diEx.getMId(), beginTime, endTime,"number","出库","零售销售",depotId,idList);
////                    BigDecimal OutSum = depotItemService.buyOrSale("出库", "销售", diEx.getMId(), beginTime, endTime,"number","到货","厂家到货",depotId,idList);
////                    BigDecimal InSumRetail = depotItemService.buyOrSale("入库", "零售退货", diEx.getMId(), beginTime, endTime,"number","入库","仓库退货",depotId,idList);
////                    BigDecimal InSum = depotItemService.buyOrSale("入库", "销售退货", diEx.getMId(), beginTime, endTime,"number","其它","直发销售退货",depotId,idList);
////                    BigDecimal OutSumRetailPrice = depotItemService.buyOrSale("出库", "零售", diEx.getMId(), beginTime, endTime,"price","出库","零售销售",depotId,idList);
////                    BigDecimal OutSumPrice = depotItemService.buyOrSale("出库", "销售", diEx.getMId(), beginTime, endTime,"price","到货","厂家到货",depotId,idList);
////                    BigDecimal InSumRetailPrice = depotItemService.buyOrSale("入库", "零售退货", diEx.getMId(), beginTime, endTime,"price","入库","仓库退货",depotId,idList);
////                    BigDecimal InSumPrice = depotItemService.buyOrSale("入库", "销售退货", diEx.getMId(), beginTime, endTime,"price","其它","直发销售退货",depotId,idList);
//
//                    BigDecimal OutSumRetail = diEx.getOutSumRetail();
//                    BigDecimal OutSum = diEx.getOutSum();
//                    BigDecimal InSumRetail = diEx.getInSumRetail();
//                    BigDecimal InSum = diEx.getInSum();
//                    BigDecimal OutSumRetailPrice = diEx.getOutSumRetailPrice();
//                    BigDecimal OutSumPrice = diEx.getOutSumPrice();
//                    BigDecimal InSumRetailPrice =  diEx.getInSumRetailPrice();
//                    BigDecimal InSumPrice = diEx.getInSumPrice();
//
//                    BigDecimal OutInSumPrice = (OutSumRetailPrice.add(OutSumPrice)).subtract(InSumRetailPrice.add(InSumPrice));
//                    BigDecimal outAll = OutSumRetail.add(OutSum);
//
//
//                    item.put("cost", diEx.getPurchaseDecimal());
//                    item.put("costAmount", diEx.getCostAmount());
//                    item.put("barCode", diEx.getBarCode());
//                    item.put("color", diEx.getMColor());
//                    item.put("materialName", diEx.getMName());
//                    item.put("materialModel", diEx.getMModel());
//                    item.put("materialStandard", diEx.getMStandard());
//                    //扩展信息
//                    String materialOther = getOtherInfo(mpArr, diEx);
//                    item.put("materialOther", materialOther);
//                    item.put("materialColor", diEx.getMColor());
//                    item.put("materialUnit", diEx.getMaterialUnit());
//                    item.put("unitName", diEx.getUnitName());
//                    item.put("outSum",outAll);
//                    item.put("inSum", InSumRetail.add(InSum));
//                    item.put("outSumPrice", OutSumRetailPrice.add(OutSumPrice));
//                    item.put("inSumPrice", InSumRetailPrice.add(InSumPrice));
//                    item.put("outInSumPrice",OutInSumPrice);//实际销售金额
//                    item.put("depotName",diEx.getDepotName());
//                    item.put("commodityDecimal",diEx.getCommodityDecimal());
//                    item.put("wholesaleDecimal",diEx.getWholesaleDecimal());
//                    item.put("categoryName",diEx.getCategoryName());
//                    dataArray.add(item);
//                }
//            }
//            map.put("rows", dataArray);
//            res.code = 200;
//            res.data = map;
//        } catch(Exception e){
//            e.printStackTrace();
//            res.code = 500;
//            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
//        }
//        return res;
//    }

//    @GetMapping(value = "/saleOut")
//    @ApiOperation(value = "销售统计")
//    public BaseResponseInfo saleOut(@RequestParam("currentPage") Integer currentPage,
//                                    @RequestParam("pageSize") Integer pageSize,
//                                    @RequestParam("beginTime") String beginTime,
//                                    @RequestParam("endTime") String endTime,
//                                    @RequestParam("materialParam") String materialParam,
//                                    @RequestParam(value = "depotId", required = false) String depotId,
//                                    @RequestParam(value = "categoryId", required = false) String categoryId,
//                                    @RequestParam("mpList") String mpList,
//                                    HttpServletRequest request)throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        String lanCode = redisService.getLanCodeFromSession(request);
//        Map<String, Object> map = new HashMap<String, Object>();
//        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
//        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
//        try {
//            List<String> idList = new ArrayList<>();
//            if(StringUtil.isNotEmpty(categoryId)){
//                idList = materialService.getListByParentId(categoryId);
//            }
//            List<DepotItemVo4WithInfoEx> dataList = depotItemService.getListWithBugOrSale(StringUtil.toNull(materialParam),
//                    "sale", beginTime, endTime,(currentPage-1)*pageSize, pageSize,depotId,idList);
//            String[] mpArr = mpList.split(",");
//            int total = depotItemService.getListWithBugOrSaleCount(StringUtil.toNull(materialParam), "sale", beginTime, endTime,depotId,idList);
//            map.put("total", total);
//            //存放数据json数组
//            JSONArray dataArray = new JSONArray();
//            if (null != dataList) {
//                for (DepotItemVo4WithInfoEx diEx : dataList) {
//                    JSONObject item = new JSONObject();
//                    item.put("cost", diEx.getPurchaseDecimal());
//                    item.put("costAmount", diEx.getCostAmount());
//                    item.put("barCode", diEx.getBarCode());
//                    item.put("color", diEx.getMColor());
//                    item.put("materialName", diEx.getMName());
//                    item.put("materialModel", diEx.getMModel());
//                    item.put("materialStandard", diEx.getMStandard());
//                    //扩展信息
//                    String materialOther = getOtherInfo(mpArr, diEx);
//                    item.put("materialOther", materialOther);
//                    item.put("materialColor", diEx.getMColor());
//                    item.put("materialUnit", diEx.getMaterialUnit());
//                    item.put("unitName", diEx.getUnitName());
//                    item.put("outSum",diEx.getOutSumRetail());
//                    item.put("inSum", diEx.getInSumRetail());
//                    item.put("outSumPrice", diEx.getOutSumRetailPrice());
//                    item.put("inSumPrice", diEx.getInSumRetailPrice());
//                    item.put("outInSumPrice",diEx.getOutInSumPrice());//实际销售金额
//                    item.put("depotName",diEx.getDepotName());
//                    item.put("commodityDecimal",diEx.getCommodityDecimal());
//                    item.put("wholesaleDecimal",diEx.getWholesaleDecimal());
//                    item.put("categoryName",diEx.getCategoryName());
//                    dataArray.add(item);
//                }
//            }
//            map.put("rows", dataArray);
//            res.code = 200;
//            res.data = map;
//        } catch(Exception e){
//            e.printStackTrace();
//            res.code = 500;
//            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
//        }
//        return res;
//    }

    @GetMapping(value = "/saleOut")
    @ApiOperation(value = "销售统计")
    public BaseResponseInfo saleOut(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("beginTime") String beginTime,
                                    @RequestParam("endTime") String endTime,
                                    @RequestParam("materialParam") String materialParam,
                                    @RequestParam(value = "depotId", required = false) String depotId,
                                    @RequestParam(value = "categoryId", required = false) String categoryId,
                                    @RequestParam("mpList") String mpList,
                                    HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
        try {
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotItemVo4WithInfoEx> dataList = depotItemService.saleOut(StringUtil.toNull(materialParam),
                    "sale", beginTime, endTime,(currentPage-1)*pageSize, pageSize,depotId,idList);
            String[] mpArr = mpList.split(",");
            int total = depotItemService.saleOutCount(StringUtil.toNull(materialParam), "sale", beginTime, endTime,depotId,idList);
            map.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("cost", diEx.getPurchaseDecimal());
                    item.put("costAmount", diEx.getCostAmount());
                    item.put("barCode", diEx.getBarCode());
                    item.put("color", diEx.getMColor());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(mpArr, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
                    item.put("materialUnit", diEx.getMaterialUnit());
                    item.put("unitName", diEx.getUnitName());
                    item.put("outSum",diEx.getOutSumRetail());
                    item.put("inSum", diEx.getInSumRetail());
                    item.put("outSumPrice", diEx.getOutSumRetailPrice());
                    item.put("inSumPrice", diEx.getInSumRetailPrice());
                    item.put("outInSumPrice",diEx.getOutInSumPrice());//实际销售金额
                    item.put("depotName",diEx.getDepotName());
                    item.put("commodityDecimal",diEx.getCommodityDecimal());
                    item.put("wholesaleDecimal",diEx.getWholesaleDecimal());
                    item.put("categoryName",diEx.getCategoryName());
                    dataArray.add(item);
                }
            }
            map.put("rows", dataArray);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
    /**
     * 获取单位
     * @param materialUnit
     * @param uName
     * @return
     */
    public String getUName(String materialUnit, String uName) {
        String unitName = null;
        if(StringUtil.isNotEmpty(materialUnit)) {
            unitName = materialUnit;
        } else if(StringUtil.isNotEmpty(uName)) {
            unitName = uName;
        }
        return unitName;
    }

    /**
     * 库存预警报表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/findStockWarningCount")
    @ApiOperation(value = "库存预警报表")
    public BaseResponseInfo findStockWarningCount(@RequestParam("currentPage") Integer currentPage,
                                                  @RequestParam("pageSize") Integer pageSize,
                                                  @RequestParam("materialParam") String materialParam,
                                                  @RequestParam(value = "depotId", required = false) String depotId,
                                                  @RequestParam("mpList") String mpList,
                                                  HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if(StringUtils.isNotEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            String[] mpArr = mpList.split(",");
            List<DepotItemStockWarningCount> list = depotItemService.findStockWarningCount((currentPage-1)*pageSize, pageSize, materialParam, depotList);
            //存放数据json数组
            if (null != list) {
                for (DepotItemStockWarningCount disw : list) {
                    DepotItemVo4WithInfoEx diEx = new DepotItemVo4WithInfoEx();
                    diEx.setMMfrs(disw.getMMfrs());
                    diEx.setMOtherField1(disw.getMOtherField1());
                    diEx.setMOtherField2(disw.getMOtherField2());
                    diEx.setMOtherField3(disw.getMOtherField3());
                    disw.setMaterialOther(getOtherInfo(mpArr, diEx));
                    disw.setMaterialUnit(getUName(disw.getMaterialUnit(), disw.getUnitName()));
                    if(disw.getCurrentNumber().compareTo(disw.getLowSafeStock())<0) {
                        disw.setLowCritical(disw.getLowSafeStock().subtract(disw.getCurrentNumber()));
                        disw.setHighCritical(BigDecimal.ZERO);
                    }
                    if(disw.getCurrentNumber().compareTo(disw.getHighSafeStock())>0) {
                        disw.setLowCritical(BigDecimal.ZERO);
                        disw.setHighCritical(disw.getCurrentNumber().subtract(disw.getHighSafeStock()));
                    }
                }
            }
            int total = depotItemService.findStockWarningCountTotal(materialParam, depotList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
    @GetMapping(value = "/findInStockWarning")
    @ApiOperation(value = "智能补货-库存预警报表")
    public BaseResponseInfo findInStockWarning(@RequestParam("currentPage") Integer currentPage,
                                                  @RequestParam("pageSize") Integer pageSize,
                                                  @RequestParam("materialParam") String materialParam,
                                                  @RequestParam(value = "depotId", required = false) String depotId,
                                                  @RequestParam("mpList") String mpList,
                                                 HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if(StringUtils.isNotEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            String[] mpArr = mpList.split(",");
            List<DepotItemStockWarningCount> list = depotItemService.findInStockWarning((currentPage-1)*pageSize, pageSize, materialParam, depotList);
            //存放数据json数组
            if (null != list) {
                for (DepotItemStockWarningCount disw : list) {
                    DepotItemVo4WithInfoEx diEx = new DepotItemVo4WithInfoEx();
                    diEx.setMMfrs(disw.getMMfrs());
                    diEx.setMOtherField1(disw.getMOtherField1());
                    diEx.setMOtherField2(disw.getMOtherField2());
                    diEx.setMOtherField3(disw.getMOtherField3());
                    disw.setMaterialOther(getOtherInfo(mpArr, diEx));
                    disw.setMaterialUnit(getUName(disw.getMaterialUnit(), disw.getUnitName()));
                    if(disw.getCurrentNumber().compareTo(disw.getLowSafeStock())<0) {
                        disw.setLowCritical(disw.getLowSafeStock().subtract(disw.getCurrentNumber()));
                    }
                    if(disw.getCurrentNumber().compareTo(disw.getHighSafeStock())>0) {
                        disw.setLowCritical(BigDecimal.ZERO);
                    }
                    MaterialExtend materialExtend = materialExtendService.getInfoByMeId(disw.getMeId());
                    //获取最近一条采购价
                    BigDecimal recentPurchase = depotItemService.getItemByHeaderIdAndBarcode(materialExtend.getId(),disw.getOrganId(),disw.getMId());
                    disw.setLastPurchasePrice(recentPurchase);
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(new Date());
                    rightNow.add(Calendar.DATE, 5);
                    Date dt1 = rightNow.getTime();
                    disw.setArrivalTime(Tools.getCenternTime(dt1));
                }
            }
            int total = depotItemService.findStockWarningCountTotal(materialParam, depotList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 统计采购、销售、零售的总金额
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/buyOrSalePrice")
    @ApiOperation(value = "统计采购、销售、零售的总金额")
    public BaseResponseInfo buyOrSalePrice(HttpServletRequest request, HttpServletResponse response)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> list = Tools.getLastMonths(6);
            JSONArray buyPriceList = new JSONArray();
            for(String month: list) {
                JSONObject obj = new JSONObject();
                BigDecimal outPrice = depotItemService.inOrOutPrice("入库", "采购", month,"其它","收费确认");
                BigDecimal inPrice = depotItemService.inOrOutPrice("出库", "采购退货", month,"其它","直发采购退货");
                obj.put("x", month);
                obj.put("y", outPrice.subtract(inPrice));
                BigDecimal outMoney = accountHeadService.inOrOutMoney( month,"1");
                obj.put("z", outMoney);
                buyPriceList.add(obj);
            }
            map.put("buyPriceList", buyPriceList);
            JSONArray salePriceList = new JSONArray();
            for(String month: list) {
                JSONObject obj = new JSONObject();
                BigDecimal outPrice = depotItemService.inOrOutPrice("出库", "销售", month,"到货","厂家到货");
                BigDecimal inPrice = depotItemService.inOrOutPrice("入库", "销售退货", month,"其它","直发销售退货");
                obj.put("x", month);
                obj.put("y", outPrice.subtract(inPrice));
                BigDecimal outMoney = accountHeadService.inOrOutMoney( month,"2");
                obj.put("z", outMoney);
                salePriceList.add(obj);
            }
            map.put("salePriceList", salePriceList);
            JSONArray retailPriceList = new JSONArray();
            for(String month: list) {
                JSONObject obj = new JSONObject();
                BigDecimal outPrice = depotItemService.inOrOutRetailPrice("出库", "零售", month,"出库","零售销售");
                BigDecimal inPrice = depotItemService.inOrOutRetailPrice("入库", "零售退货", month,"入库","仓库退货");
                obj.put("x", month);
                obj.put("y", outPrice.subtract(inPrice));
                BigDecimal outMoney = depotItemService.inOrOutRetailMoney(month);
                obj.put("z", outMoney);
                retailPriceList.add(obj);
            }
            map.put("retailPriceList", retailPriceList);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data =  "zh".equals(lanCode) ? "统计失败" : "Statistical failure";
        }
        return res;
    }

    /**
     * 获取批次商品列表信息
     * @param request
     * @return
     */
    @GetMapping(value = "/getBatchNumberList")
    @ApiOperation(value = "获取批次商品列表信息")
    public BaseResponseInfo getBatchNumberList(@RequestParam("name") String name,
                                               @RequestParam("depotId") String depotId,
                                               @RequestParam("meId") String meId,
                                               @RequestParam(value = "batchNumber", required = false) String batchNumber,
                                               HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<>();
        try {
            List<DepotItemVoBatchNumberList> reslist = new ArrayList<>();
            List<DepotItemVoBatchNumberList> list = depotItemService.getBatchNumberList(name, depotId, meId, batchNumber);
            for(DepotItemVoBatchNumberList bn: list) {
                if(bn.getTotalNum()!=null && bn.getTotalNum().compareTo(BigDecimal.ZERO)>0) {
                    reslist.add(bn);
                }
                bn.setExpirationDateStr(Tools.parseDateToStr(bn.getExpirationDate()));
            }
            map.put("rows", reslist);
            map.put("total", reslist.size());
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }


    @GetMapping(value = "/findRebateDetail")
    @ApiOperation(value = "单据明细列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "执行成功",response = DepotItemVo4WithInfoEx.class)
    })
    public BaseResponseInfo findRebateDetail(@RequestParam("headerId") String headerId,
                                          HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotItemVo4WithInfoEx> dataList = new ArrayList<DepotItemVo4WithInfoEx>();
            if(!StringUtil.isEmpty(headerId)) {
                dataList = depotItemService.findRebateDetail(headerId);
            }
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            outer.put("rows", dataList);
            res.code = 200;
            res.data = outer;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/saleOutDetail")
    @ApiOperation(value = "销售统计明细")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotItemVo4WithInfoEx.class)
    })
    public BaseResponseInfo saleOutDetail(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("beginTime") String beginTime,
                                    @RequestParam("endTime") String endTime,
                                    @RequestParam("materialParam") String materialParam,
                                    @RequestParam(value = "depotId", required = false) String depotId,
                                    @RequestParam(value = "categoryId", required = false) String categoryId,
                                    HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
        try {
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotItemVo4WithInfoEx> dataList = depotItemService.getListWithBugOrSaleDetail(StringUtil.toNull(materialParam),
                    "sale", beginTime, endTime,(currentPage-1)*pageSize, pageSize,depotId,idList);
            int total = depotItemService.getListWithBugOrSaleDetailCount(StringUtil.toNull(materialParam), "sale", beginTime, endTime,depotId,idList);
            map.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();

                    //采购平均价
                    BigDecimal cost = depotItemService.findMaterialCost(diEx.getMId());
                    if (cost.compareTo(BigDecimal.ZERO)>0){
                        item.put("cost", cost);
                        item.put("costAmount", cost.multiply(diEx.getOperNumber()));
                    }else {
                        BigDecimal purchaseDecimal = diEx.getPurchaseDecimal();
                        item.put("cost", purchaseDecimal);
                        if (purchaseDecimal.compareTo(BigDecimal.ZERO)>0){
                            item.put("costAmount", purchaseDecimal.multiply(diEx.getOperNumber()));
                        }else {
                            item.put("costAmount", "-");
                        }
                    }
                    item.put("barCode", diEx.getBarCode());
                    item.put("color", diEx.getMColor());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    item.put("materialColor", diEx.getMColor());
                    item.put("materialUnit", diEx.getMaterialUnit());
                    item.put("unitName", diEx.getUnitName());
                    item.put("outSum", diEx.getOperNumber());
                    item.put("inSum", diEx.getRefundOperNumber());
                    item.put("outSumPrice",  diEx.getAllPrice());
                    item.put("inSumPrice",  diEx.getRefundAllPrice());
                    BigDecimal outInSumPrice = diEx.getAllPrice().subtract(diEx.getRefundAllPrice());
                    item.put("outInSumPrice",outInSumPrice);//实际销售金额
                    item.put("depotName",diEx.getDepotName());
                    item.put("commodityDecimal",diEx.getCommodityDecimal());
                    item.put("wholesaleDecimal",diEx.getWholesaleDecimal());
                    item.put("categoryName",diEx.getCategoryName());
                    item.put("number",diEx.getNumber());
                    item.put("operTimeStr",diEx.getOperTimeStr());
                    dataArray.add(item);
                }
            }
            map.put("rows", dataArray);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
}
